﻿@using System.Linq.Expressions;
@using BlazorComponent;
@using Masa.Blazor.Presets;
@using Microsoft.AspNetCore.Authorization;
@using Microsoft.Extensions.DependencyInjection
@using ThingsGateway.Admin.Application;
@using ThingsGateway.Admin.Blazor
@using ThingsGateway.Core.Extension
@using ThingsGateway.Gateway.Application

@namespace ThingsGateway.Gateway.Blazor
@attribute [Authorize]
@inject UserResoures UserResoures
@attribute [RolePermission]
@inherits BaseComponentBase

@code {
    private List<Channel> _queryChannels = new();
    private List<Device> _queryDevices = new();
    private List<PluginOutput> _queryPluginOutputs = new();
    private void PluginQuerySelections(string v)
    {
        if (string.IsNullOrEmpty(v))
        {
            return;
        }
        _queryPluginOutputs = _pluginOutputs.SelectMany(a => a.Children).Where(e => e.Name.ToLowerInvariant().IndexOf(v.ToLowerInvariant()) > -1)
        .OrderBy(a => a.Name.Length).Take(20).ToList();
    }
    private void DeviceQuerySelections(string v)
    {
        if (string.IsNullOrEmpty(v))
        {
            return;
        }
        _queryDevices = _devices.Where(e => e.Name.ToLowerInvariant().IndexOf(v.ToLowerInvariant()) > -1).OrderBy(a => a.Name.Length).Take(20).ToList();
    }
    private void ChannelQuerySelections(string v)
    {
        if (string.IsNullOrEmpty(v))
        {
            return;
        }
        _queryChannels = _channels.Where(e => e.Name.ToLowerInvariant().IndexOf(v.ToLowerInvariant()) > -1).OrderBy(a => a.Name.Length).Take(20).ToList();
    }
}
<AppDataTable @ref="_datatable" TItem="Device" SearchItem="DevicePageInput" AddItem="DeviceAddInput" EditItem="DeviceEditInput"
              SearchModel="@_search" IsShowSearchKey
               QueryCallAsync="QueryCallAsync" AddCallAsync="AddCallAsync"
               EditCallAsync="EditCallAsync" DeleteCallAsync="DeleteCallAsync"
               IsMenuOperTemplate=false AddWidth="1600" EditWidth="1600"
                IsShowDetailButton
                IsShowQueryButton
               IsShowAddButton=@UserResoures.IsHasButtonWithRole($"{RolePrex}Add")
               IsShowDeleteButton=@UserResoures.IsHasButtonWithRole($"{RolePrex}Delete")
               IsShowEditButton=@UserResoures.IsHasButtonWithRole($"{RolePrex}Edit")>

     <SearchTemplate>

         <MAutocomplete Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1 mx-2 " CacheItems HideNoData Outlined
                        ItemValue="r=>r.Id" ItemText="r=>r.Name" OnSearchInputUpdate="ChannelQuerySelections"
                        Items="_queryChannels" Flat Clearable
                        @bind-Value="context.ChannelId" Label=@AppService.I18n.T(context.Description(x => x.ChannelId)) />

         <MAutocomplete Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1 mx-2 " CacheItems HideNoData Outlined
                        ItemValue="r=>r.Name" ItemText="r=>r.Name" OnSearchInputUpdate="DeviceQuerySelections"
                        Items="_queryDevices" Flat Clearable
                        @bind-Value="context.Name" Label=@AppService.I18n.T(context.Description(x => x.Name)) />

         <MAutocomplete Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1 mx-2 " CacheItems HideNoData Outlined
                        ItemValue="r=>r.FullName" ItemText="r=>r.Name" OnSearchInputUpdate="PluginQuerySelections"
                        Items="_queryPluginOutputs" Flat Clearable
                        @bind-Value="context.PluginName" Label=@AppService.I18n.T(context.Description(x => x.PluginName)) />


     </SearchTemplate>

     <AddTemplate>
         @GetRenderFragment(context)

    </AddTemplate>

    <EditTemplate>
        @GetRenderFragment(context)
    </EditTemplate>


    <OtherToolbarTemplate>

        <MMenu OffsetY Context="menu">
             <ActivatorContent>
                 <MButton @attributes="@menu.Attrs" Color="primary"
                          Class="my-1  mx-2 ">
                     @AppService.I18n.T("导出")
                    <AppChevronDown></AppChevronDown>
                </MButton>
            </ActivatorContent>
            <ChildContent>
                <MList>
                    <MListItem OnClick="()=>DownExportAsync(true)">@AppService.I18n.T("导出全部")</MListItem>
                        <MListItem OnClick="()=>DownExportAsync(false)">@AppService.I18n.T("导出搜索项")</MListItem>
                    </MList>
                </ChildContent>
            </MMenu>

            <MButton Disabled=@(!UserResoures.IsHasButtonWithRole($"{RolePrex}Add")) Class="mx-2 my-1" OnClick=@(()=>CopyClickAsync(context)) Color="primary">@AppService.I18n.T("复制")</MButton>
            <MButton Disabled=@(!UserResoures.IsHasButtonWithRole($"{RolePrex}Edit")) Class="mx-2 my-1" OnClick=@(()=>RefreshClickAsync()) Color="primary">@AppService.I18n.T("刷新动态属性")</MButton>
            <MButton Disabled=@(!UserResoures.IsHasButtonWithRole($"{RolePrex}Import")) Class=" mx-2 my-1 " OnClick=@(ImportClickAsync) Color="primary">
                @AppService.I18n.T("导入")
        </MButton>
        <MButton Disabled=@(!UserResoures.IsHasButtonWithRole($"{RolePrex}Clear")) Class="mx-2 my-1" OnClick=@(()=>DeleteAllAsync()) Color="primary">@AppService.I18n.T("清空")</MButton>
        </OtherToolbarTemplate>

        <ItemColTemplate>
            @switch (context.Header.Value)
        {
            case nameof(context.Item.Enable):
                <EnableChip Value="context.Item.Enable">
                </EnableChip>
                break;
            case nameof(context.Item.ChannelId):
                @(_channels.FirstOrDefault(a => a.Id == context.Item.ChannelId)?.Name)
                break;

            case nameof(context.Item.PluginName):
                @context.Value?.ToString().GetFileNameAndTypeName().Item2
                break;
            default:
                @if (context.Header.CellClass?.Contains("text-truncate") == true)
                {
                    <span title=@context.Value>
                        @context.Value
                    </span>
                }
                else
                {
                    @context.Value
                }
                break;
        }

    </ItemColTemplate>
</AppDataTable>



@code {

    RenderFragment GetRenderFragment(DeviceAddInput context)
    {
        RenderFragment renderFragment =
    @<div style="min-height:800px;">
        <MTabs @bind-Value="tab" Class="" Style="">
            <MTab Value=1>    @AppService.I18n.T("设备属性")    </MTab>
            <MTab Value=2>    @AppService.I18n.T("插件属性")    </MTab>


        </MTabs>
        <MTabsItems Value="tab">
            <MTabItem Value="1">
                <MCard Flat Elevation="0" Class="ma-5">
                    <MContainer>
                        <MRow Justify="JustifyTypes.Start" Align="AlignTypes.Center">

                            <MCol Md=12 Cols=12>
                                <MSubheader Style="max-height:24px" Class="font-weight-black text-subtitle-1">
                                    @AppService.I18n.T("基础属性")
                                </MSubheader>
                            </MCol>

                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Name Label="@(context.Description(x => x.Name))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Description Label="@(context.Description(x => x.Description))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px"
                                            Type="number" NumberProps=@(prop => { prop.Min = 10; prop.Step = 10; })
                                            Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.IntervalTime Label="@(context.Description(x => x.IntervalTime))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                            </MCol>

                            <MCol Md=3 Cols=12>
                                <MRadioGroup @bind-Value=@context.Enable Label=@(context.Description(x => x.Enable))
                                             Style="max-width:300px"
                                             Row Dense HideDetails="@("auto")">
                                    <MRadio Label=@AppService.I18n.T("是") Value=true></MRadio>
                                    <MRadio Label=@AppService.I18n.T("否") Value=false></MRadio>
                                </MRadioGroup>
                            </MCol>


                        </MRow>

                        <MRow Class="mt-5" Justify="JustifyTypes.Start" Align="AlignTypes.Center">
                            <MCol Md=12 Cols=12>
                                <MSubheader Style="max-height:24px" Class="font-weight-black text-subtitle-1">
                                    @AppService.I18n.T("通道选择")
                                </MSubheader>
                            </MCol>


                            <MCol Md=3 Cols=12>
                                <MAutocomplete Dense Style="max-width:300px;" HideDetails=@("auto") CacheItems HideNoData Outlined
                                               ItemValue="r=>r.Id" ItemText="r=>r.Name" OnSearchInputUpdate="ChannelQuerySelections"
                                               Items="_queryChannels" Flat Clearable
                                               @bind-Value="context.ChannelId" Label=@AppService.I18n.T(context.Description(x => x.ChannelId)) />

                            </MCol>
                        </MRow>

                        <MRow Class="mt-5" Justify="JustifyTypes.Start" Align="AlignTypes.Center">
                            <MCol Md=12 Cols=12>
                                <MSubheader Style="max-height:24px" Class="font-weight-black text-subtitle-1">
                                    @AppService.I18n.T("插件选择")
                                </MSubheader>
                            </MCol>


                            <MCol Md=3 Cols=12>
                                <MCascader Value="context.PluginName" ValueChanged=@(async a=>await DriverValueChangedAsync(context,a)) Label="@(typeof(CollectDeviceRunTime).GetDescription(nameof(CollectDeviceRunTime.PluginName)))"
                                           TValue=string TItem="PluginOutput" Outlined Style="max-width:300px" ValueExpression="()=>context.PluginName"
                                           Items="_pluginOutputs" ItemText="u => u.Name" ItemValue="u => u.FullName" ItemChildren="u => u.Children"
                                           MenuProps="@(props => { props.Auto = true; props.OffsetY = true; })"
                                           ShowAllLevels="false" HideDetails="false" Height="30" Dense>
                                </MCascader>
                            </MCol>
                        </MRow>


                        <MRow Class="mt-5" Justify="JustifyTypes.Start" Align="AlignTypes.Center">
                            <MCol Md=12 Cols=12>
                                <MSubheader Style="max-height:24px" Class="font-weight-black text-subtitle-1">
                                    @AppService.I18n.T("冗余配置")
                                </MSubheader>
                            </MCol>


                            <MCol Md=3 Cols=12>
                                <MRadioGroup @bind-Value=@context.IsRedundant Label=@(context.Description(x => x.IsRedundant))
                                             Style="max-width:300px"
                                             Row Dense HideDetails="@("auto")">
                                    <MRadio Label=@AppService.I18n.T("是") Value=true></MRadio>
                                    <MRadio Label=@AppService.I18n.T("否") Value=false></MRadio>
                                </MRadioGroup>
                            </MCol>

                            <MCol Md=3 Cols=12>
                                <MAutocomplete Dense Style="max-width:300px;" HideDetails=@("auto") CacheItems HideNoData Outlined
                                               ItemValue="r=>r.Id" ItemText="r=>r.Name" OnSearchInputUpdate="DeviceQuerySelections"
                                               Items="_queryDevices" Flat Clearable ItemDisabled="u => (u.PluginName!=context.PluginName||u.Id==context.Id)"
                                               @bind-Value=@context.RedundantDeviceId Label="@context.Description(x=>x.RedundantDeviceId)" />

                            </MCol>

                        </MRow>


                        <MRow Class="mt-5" Justify="JustifyTypes.Start" Align="AlignTypes.Center">
                            <MCol Md=12 Cols=12>
                                <MSubheader Style="max-height:24px" Class="font-weight-black text-subtitle-1">
                                    @AppService.I18n.T("备用字段")
                                </MSubheader>
                            </MCol>


                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Remark1 Label="@(context.Description(x => x.Remark1))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Remark2 Label="@(context.Description(x => x.Remark2))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Remark3 Label="@(context.Description(x => x.Remark3))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Remark4 Label="@(context.Description(x => x.Remark4))" />
                            </MCol>
                            <MCol Md=3 Cols=12>
                                <MTextField Dense Style="max-width:300px" Outlined HideDetails="@("auto")" Color="primary" @bind-Value=@context.Remark5 Label="@(context.Description(x => x.Remark5))" />
                            </MCol>
                        </MRow>
                    </MContainer>
                </MCard>
            </MTabItem>

            <MTabItem Value="2">
                <MCard Flat Elevation="0" Class="ma-5">

                    <MContainer>
                        <MRow Justify="JustifyTypes.Start" Align="AlignTypes.Center">

                            <MCol Md=12 Cols=12 Class="mb-5">
                                <MButton Class="mx-2 my-1" OnClick=@(()=>RefreshClickAsync(context)) Color="primary">@AppService.I18n.T("刷新动态属性")</MButton>
                            </MCol>
                            @if (context.DevicePropertys != null)
                        {
                            @foreach (var item in context.DevicePropertys.ToList())
                        {
                        var data=PluginService.GetDriverPropertyTypes(context.PluginName);
                        if(data.ContainsKey(item.Name))
                        {

                        var isBigText=item.Name.Contains("BigText");
                        int md=isBigText?12:4;
                            <MCol Md=md Cols=12>
                                <DynamicPropertyComponent IsBigText=isBigText Type="data[item.Name].PropertyType" @bind-Value=item.Value
                                                          Description=@(item.Description) Remark=@(data[item.Name].Remark)>
                                </DynamicPropertyComponent>
                            </MCol>
                        }
                        else
                        {
                        context.DevicePropertys.Remove(item);
                        }
                        }
                        }
                        </MRow>

                    </MContainer>
                </MCard>
            </MTabItem>

        </MTabsItems>
    </div>
        ;
        return renderFragment;
    }
    private StringNumber tab;
}

